package com.mxdx.edu.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.github.pagehelper.StringUtil;
import com.mxdx.edu.service.IRecruitmentDictService;
import com.mxdx.edu.util.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mxdx.edu.model.Dict;
import com.mxdx.edu.service.ICacheService;
import com.mxdx.edu.service.IDictService;

/**
 * 缓存商户简称
 * 
 * @author WangYuan
 * @since 2016-02-29 19:00
 *
 */

@Service
public class CacheService implements ICacheService {

	@Resource
	private IDictService dictService;

	public LoadingCache<String, List<Dict>> dictList;

	public LoadingCache<String, Map<String,Object>> placeMap;

	@Resource
	private IRecruitmentDictService recruitmentDictService;
	@PostConstruct
	public void init() {
		this.dictList = CacheBuilder.newBuilder().maximumSize(2000)
				.expireAfterWrite(5, TimeUnit.MINUTES)
				.build(new CacheLoader<String, List<Dict>>() {
					@Override
					public List<Dict> load(String key) throws Exception {
						return dictService.findTypeList(key);
					}
				});

		this.placeMap = CacheBuilder.newBuilder().maximumSize(2000)
				.expireAfterWrite(30, TimeUnit.MINUTES)
				.build(new CacheLoader<String,  Map<String, Object>>() {
					@Override
					public Map<String, Object> load(String key) throws Exception {
						Map<String, Object> param = new HashMap<>();
						param.put("id",key);
						List<Map<String, Object>> paramMapList = recruitmentDictService.findListByMap(param);
						if(paramMapList != null && paramMapList.size()>0){
							return paramMapList.get(0);
						}
						return param;
					}
				});
	}




	@Override
	public List<Dict> getDictList(String key) {
		try {
			return dictList.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Map<String, Object> getPlace(String key) {
		if(StringUtils.isEmpty(key)){
			return new HashMap<>();
		}
		try {
			return placeMap.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
